﻿using MiniExcelLibs;
using RemoteManger.Entity;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RemoteManger.Remote
{
 
    public partial class RemoteMain : Form
    {
        private int childFormNumber = 0;
        protected SqlSugarScopeProvider db = null;

        public RemoteMain()
        {
            InitializeComponent();
            SqlHelper.Init();
            db = SqlHelper.GetInstance();
            db.DbMaintenance.CreateDatabase();
            db.CodeFirst.InitTables(typeof(MachineInfo));// 
            db.CodeFirst.InitTables(typeof(MachineGroupInfo));//
        }
        public virtual void RefushData()
        {

        }
        private void ShowNewForm(object sender, EventArgs e)
        {
            Form childForm = new Form();
            childForm.MdiParent = this;
            childForm.Text = "窗口 " + childFormNumber++;
            childForm.Show();
        }




        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void AddLink_Click(object sender, EventArgs e)
        {
            new GroupEdit().Show();
        }

        private void MDIParent1_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 下载分组模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    string selectedFolder = folderBrowserDialog.SelectedPath;
                    DataTable table = new DataTable();
                    table.TableName = "分组信息";
                    table.Columns.Add("分组名称");
                    table.Columns.Add("备注");
                    string filepath = Path.Combine(selectedFolder, $"分组信息模板_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");
                    MiniExcel.SaveAs(filepath, table);
                    MessageBox.Show("下载成功");

                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("下载失败：" + ex.Message);

            }

        }

        /// <summary>
        /// 分组信息导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            OpenFileDialog saveFileDialog = new OpenFileDialog();
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Filter = "表格文件(*.xlsx)|*.xlsx|表格文件(*.xls)|*.xls|表格文件(*.csv)|*.csv";
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = saveFileDialog.FileName;

                DataTable dt = MiniExcel.QueryAsDataTable(FileName, useHeaderRow: true);
                List<MachineGroupInfo> list = new List<MachineGroupInfo>();
                if (dt != null)
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        MachineGroupInfo serverInfo = new MachineGroupInfo();
                        serverInfo.GroupName = item["分组名称"].ToNullString();
                        serverInfo.Remark = item["备注"].ToNullString();

                        serverInfo.Id = SnowFlake.GenerateId();
                        list.Add(serverInfo);
                    }
                    var x = db.Storageable(list).WhereColumns(p => p.GroupName).ToStorage();
                    x.AsInsertable.ExecuteCommand();//不存在插入
                    x.AsUpdateable.ExecuteCommand();//不存在插入
                    MessageBox.Show("导入成功");
                    RefushData();
                }
            }
        }
        /// <summary>
        /// 下载服务器资料模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    string selectedFolder = folderBrowserDialog.SelectedPath;
                    DataTable table = new DataTable();
                    table.TableName = "服务器信息模板";
                    table.Columns.Add("分组名称");
                    table.Columns.Add("名称");
                    table.Columns.Add("IP");
                    table.Columns.Add("端口");
                    table.Columns.Add("账号");
                    table.Columns.Add("密码");
                    table.Columns.Add("备注");
                    string filepath = Path.Combine(selectedFolder, $"服务器信息模板_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls");
                    MiniExcel.SaveAs(filepath, table);
                    MessageBox.Show("下载成功");

                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("下载失败：" + ex.Message);

            }

        }
        /// <summary>
        /// 服务器导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            OpenFileDialog saveFileDialog = new OpenFileDialog();
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Filter = "表格文件(*.xls)|*.xls|表格文件(*.xlsx)|*.xlsx|表格文件(*.csv)|*.csv";
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = saveFileDialog.FileName;
                DataTable dt = MiniExcel.QueryAsDataTable(FileName, useHeaderRow: true);
                var groups = db.Queryable<MachineGroupInfo>().ToDictionary(p => p.GroupName, p => p.Id);
                List<MachineInfo> list = new List<MachineInfo>();
                if (dt != null)
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        MachineInfo serverInfo = new MachineInfo();
                        serverInfo.Title = item["名称"].ToNullString();
                        serverInfo.Ip = item["IP"].ToNullString();
                        serverInfo.Port = item["端口"].ToInt();
                        serverInfo.UserName = item["账号"].ToNullString();
                        serverInfo.Password = item["密码"].ToNullString();
                        serverInfo.Remark = item["备注"].ToNullString();
                        string graoupName = item["分组名称"].ToNullString();
                        if (!groups.Keys.Contains(graoupName))
                        {
                            MachineGroupInfo group = new MachineGroupInfo();
                            group.GroupName = graoupName;
                            group.Remark = "";
                            group.Id = SnowFlake.GenerateId();
                            db.Insertable(group).ExecuteCommand();
                            groups.Add(graoupName, group.Id);
                        }
                        serverInfo.GroupId = groups[graoupName].ToNullString().ToLong();
                        list.Add(serverInfo);
                        //db.Insertable(serverInfo).ExecuteCommand();
                    }
                    var x = db.Storageable(list).WhereColumns(p => p.Ip).ToStorage();
                    x.AsInsertable.ExecuteCommand();//不存在插入
                    x.AsUpdateable.ExecuteCommand();//不存在插入
                    var insertList = x.InsertList.Select(z => z.Item).ToList();
                    var updateList = x.UpdateList.Select(z => z.Item).ToList();
                    MessageBox.Show("导入成功");
                    RefushData();
                }
                else
                {
                    MessageBox.Show("导入失败");
                }

            }

        }

        private void toolStripMenuItem10_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem10_Click_1(object sender, EventArgs e)
        {
            RefushData();
        }

        private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
    }
}
